package com.example.myapplication;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;

public class CameraActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera);

        ImageView imageView = findViewById(R.id.image_view);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 申请权限
                requestPermissions(new String[]{Manifest.permission.CAMERA}, 1);
            }
        });
    }

    // 动态申请权限的回调函数
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // 用户同意, 下一步跳转到相机Activity
            Intent intent = new Intent();
            intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(intent, 0);
        } else {

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 获取相机Activity返回的图片
        // requestCode用来区分是哪个activity返回了，resultCode用来判断返回的状态
        if(requestCode == 0 && resultCode == RESULT_OK) {
            // 从intent上读取数据, （intent怎么传输对象？？）
            Bundle bundle = data.getExtras();
            Bitmap bitmap = bundle.getParcelable("data");
            // 把图片设置到imageview组件上
            ImageView imageView = findViewById(R.id.image_view);
            imageView.setImageBitmap(bitmap);
        }
    }
}